package com.mgq.netty.chat.handler;

import com.mgq.netty.chat.message.GroupQuitRequestMessage;
import com.mgq.netty.chat.message.GroupQuitResponseMessage;
import com.mgq.netty.chat.session.Group;
import com.mgq.netty.chat.session.GroupSession;
import com.mgq.netty.chat.session.GroupSessionFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @author MaGuangQi

 * @date 2021-12-08 21:26
 **/
@ChannelHandler.Sharable
public class GroupQuitRequestHandler extends SimpleChannelInboundHandler<GroupQuitRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupQuitRequestMessage msg) throws Exception {
        String groupName = msg.getGroupName();
        String username = msg.getUsername();
        GroupSession groupSession = GroupSessionFactory.getGroupSession();
        Group group = groupSession.removeMember(groupName, username);
        if (group == null) {
            //组不存在
            ctx.writeAndFlush(new GroupQuitResponseMessage(false, groupName + "组不存在"));
        } else {
            ctx.writeAndFlush(new GroupQuitResponseMessage(true, "退出"+groupName+"组成功"));
            groupSession.removeMember(groupName, username);
            //广播
            groupSession.getMembersChannel(groupName).forEach(channel -> {
                channel.writeAndFlush(new GroupQuitResponseMessage(true, username + "退出群聊"));
            });
        }
    }
}
